// order-progress.js
const api = require('../../utils/api.js')
const permissionUtils = require('../../utils/permissions.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    // 筛选条件
    filterOptions: {
      orders: [],
      products: [],
      processes: []
    },
    selectedOrderId: '',
    selectedProductId: '',
    selectedProcessId: '',
    selectedOrderIndex: 0,
    selectedProductIndex: 0,
    selectedProcessIndex: 0,
    selectedOrderText: '全部',
    selectedProductText: '全部',
    selectedProcessText: '全部',
    
    // 订单进度列表
    orderList: [],
    loading: false,
    
    // 工序统计
    processStats: [],
    
    // 分页
    page: 1,
    limit: 10,
    hasMore: true
  },

  onLoad() {
    // 页面权限检查
    if (!pagePermission.requirePagePermission('pages/order-progress/order-progress')) {
      return
    }
    
    // 加载数据
    this.loadFilterOptions()
    this.loadOrderProgressList(true)
    this.loadProcessStats()
  },

  // 权限检查方法
  hasPermission(module, action) {
    const app = getApp()
    const adminInfo = app.globalData.adminInfo
    if (!adminInfo || !adminInfo.id) {
      return false
    }
    return permissionUtils.hasPermission(adminInfo.id, module, action)
  },

  // 显示权限不足提示
  showPermissionDenied(module, action) {
    const description = permissionUtils.getPermissionDescription(module, action)
    wx.showModal({
      title: '权限不足',
      content: `您没有${description}的权限`,
      showCancel: false,
      success: () => {
        wx.navigateBack()
      }
    })
  },

  // 加载筛选选项
  loadFilterOptions() {
    api.getProgressFilterOptions().then(res => {
      this.setData({
        'filterOptions.orders': res.data.orders || [],
        'filterOptions.products': res.data.products || [],
        'filterOptions.processes': res.data.processes || []
      })
    }).catch(err => {
      console.error('加载筛选选项失败:', err)
    })
  },

  // 加载订单进度列表
  loadOrderProgressList(refresh = false) {
    if (this.data.loading) return

    if (refresh) {
      this.setData({
        page: 1,
        hasMore: true,
        orderList: []
      })
    }

    this.setData({ loading: true })

    const params = {
      page: this.data.page,
      limit: this.data.limit
    }

    if (this.data.selectedOrderId) params.order_id = this.data.selectedOrderId
    if (this.data.selectedProductId) params.product_id = this.data.selectedProductId
    if (this.data.selectedProcessId) params.process_id = this.data.selectedProcessId

    api.getOrderProgressList(params).then(res => {
      const newList = refresh ? res.data.list : this.data.orderList.concat(res.data.list)
      
      this.setData({
        orderList: newList,
        hasMore: res.data.list.length === this.data.limit,
        loading: false
      })
    }).catch(err => {
      console.error('加载订单进度失败:', err)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    })
  },

  // 加载工序统计
  loadProcessStats() {
    const params = {}
    if (this.data.selectedOrderId) params.order_id = this.data.selectedOrderId
    if (this.data.selectedProductId) params.product_id = this.data.selectedProductId
    if (this.data.selectedProcessId) params.process_id = this.data.selectedProcessId

    api.getProcessProgressStats(params).then(res => {
      this.setData({
        processStats: res.data || []
      })
    }).catch(err => {
      console.error('加载工序统计失败:', err)
    })
  },

  // 筛选条件变化
  onFilterChange(e) {
    const { type } = e.currentTarget.dataset
    const value = e.detail.value

    // 根据类型获取对应的选项数组
    let options = []
    let indexKey = ''
    let textKey = ''
    let idKey = ''
    
    switch (type) {
      case 'selectedOrderId':
        options = this.data.filterOptions.orders
        indexKey = 'selectedOrderIndex'
        textKey = 'selectedOrderText'
        idKey = 'selectedOrderId'
        break
      case 'selectedProductId':
        options = this.data.filterOptions.products
        indexKey = 'selectedProductIndex'
        textKey = 'selectedProductText'
        idKey = 'selectedProductId'
        break
      case 'selectedProcessId':
        options = this.data.filterOptions.processes
        indexKey = 'selectedProcessIndex'
        textKey = 'selectedProcessText'
        idKey = 'selectedProcessId'
        break
    }

    // 如果选择了"全部"（索引为0），则清空选择
    const selectedValue = value === 0 ? '' : options[value]?.id || ''
    const selectedText = value === 0 ? '全部' : options[value]?.order_no || options[value]?.name || '全部'
    
    this.setData({
      [indexKey]: value,
      [textKey]: selectedText,
      [idKey]: selectedValue
    })

    // 重新加载数据
    this.loadOrderProgressList(true)
    this.loadProcessStats()
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadOrderProgressList(true)
    this.loadProcessStats()
    wx.stopPullDownRefresh()
  },

  // 上拉加载更多
  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.setData({
        page: this.data.page + 1
      })
      this.loadOrderProgressList()
    }
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/order-progress-detail/order-progress-detail?order_id=${orderId}`
    })
  },

  // 重置筛选
  resetFilter() {
    this.setData({
      selectedOrderId: '',
      selectedProductId: '',
      selectedProcessId: '',
      selectedOrderIndex: 0,
      selectedProductIndex: 0,
      selectedProcessIndex: 0,
      selectedOrderText: '全部',
      selectedProductText: '全部',
      selectedProcessText: '全部'
    })
    this.loadOrderProgressList(true)
    this.loadProcessStats()
  }
})
